package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.*;
import cn.wolfcode.feign.AlipayFeignApi;
import cn.wolfcode.feign.IntergralFeignApi;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.mapper.SeckillProductMapper;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.IdGenerateUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by wolfcode-lanxw
 */
@Service
@Slf4j
public class OrderInfoSeviceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;
    @Autowired
    private SeckillProductMapper seckillProductMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private AlipayFeignApi alipayFeignApi;
    @Autowired
    private IntergralFeignApi intergralFeignApi;

    @Value("${pay.returnUrl}")
    private String returnUrl;
    @Value("${pay.notifyUrl}")
    private String notifyUrl;

    @Override
    public String doSeckill(Integer time, Long seckillId, Long phone) {
        // 6.1减少真实库存
        seckillProductMapper.decrStock(seckillId);
        // 6.2创建订单并且把订单保存到数据库中  t_order_info
        String orderNo = createOrder(time,seckillId,phone);
        // 6.3redis存一个数据为重复下单做铺垫
        // seckillOrderSet:time   phone:seckillId
        redisTemplate.opsForSet().add(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""),phone+":"+seckillId + "");
        return orderNo;
    }

    private String createOrder(Integer time, Long seckillId, Long phone) {
        // redis存一个数据为重复下单做铺垫
        SeckillProductVo seckillProductVo = seckillProductService.find(time, seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(1L);
        orderInfo.setIntergral(seckillProductVo.getIntergral());
        orderInfo.setProductCount(1);
        orderInfo.setProductId(seckillProductVo.getProductId());
        orderInfo.setProductImg(seckillProductVo.getProductImg());
        orderInfo.setProductName(seckillProductVo.getProductName());
        orderInfo.setProductPrice(seckillProductVo.getProductPrice());
        orderInfo.setSeckillDate(new Date());
        orderInfo.setSeckillId(seckillProductVo.getId());
        orderInfo.setSeckillPrice(seckillProductVo.getSeckillPrice());
        orderInfo.setSeckillTime(time);
        orderInfo.setUserId(phone);
        // 雪花算法
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId() + "");
        orderInfoMapper.insert(orderInfo);
        return orderInfo.getOrderNo();
    }

    @Override
    @Transactional
    public void cancelOrder(OrderMQResult orderMQResult) {
        // 1 回补真实库存
        seckillProductMapper.incrStock(orderMQResult.getSeckillId());
        // 2 回补预库存
        seckillProductService.syncRedisStockCount(orderMQResult.getTime(),orderMQResult.getSeckillId());
        // 3 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMQResult.getSeckillId());
        // 4 修改订单状态   状态  STATUS_TIMEOUT 超时取消订单
        orderInfoMapper.updateCancelStatus(orderMQResult.getOrderNo(),OrderInfo.STATUS_TIMEOUT);
        log.info("超时取消的业务执行成功");
    }

    @Override
    public OrderInfo find(String orderNo) {
        Object objJson = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""), orderNo);
        if (StringUtils.isEmpty(objJson + "")) {
            return null;
        }
        return JSON.parseObject(objJson + "",OrderInfo.class);
    }

    @Override
    public String payOnline(String orderNo, Integer type) {
        OrderInfo orderInfo = find(orderNo);
        // 远程调用支付进行支付操作
        PayVo payVo = new PayVo();
        payVo.setOutTradeNo(orderNo);
        payVo.setTotalAmount(orderInfo.getSeckillPrice().toString());
        payVo.setBody(orderInfo.getProductName());
        payVo.setSubject(orderInfo.getProductName());
        payVo.setNotifyUrl(notifyUrl);
        payVo.setReturnUrl(returnUrl);
        // 将数据封装到payVo中
        // result data属性就是我们想要的那段from表单字符串
        Result<String> result = alipayFeignApi.payOnline(payVo);
        if(result != null && !result.hasError()) {
            return result.getData();
        }
        return null;
    }


    @Override
    public void paySuccess(Map<String, String> params) {
        String orderNo = params.get("out_trade_no");
        OrderInfo orderInfo = find(orderNo);
        // 1 插入流水记录
        PayLog payLog = new PayLog();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        payLog.setNotifyTime(simpleDateFormat.format(new Date()));
        payLog.setTradeNo(orderNo);
        payLog.setPayType(PayLog.PAY_TYPE_ONLINE);
        payLog.setTotalAmount(orderInfo.getSeckillPrice() + "");
        payLogMapper.insert(payLog);
        // 2 修改订单状态  在线支付
        orderInfoMapper.changePayStatus(orderNo,OrderInfo.STATUS_ACCOUNT_PAID,OrderInfo.PAYTYPE_ONLINE);

    }


    @Override
    @GlobalTransactional
    public void payIntergral(String orderNo, Integer type) {
        OrderInfo orderInfo = find(orderNo);
        // 插入流水记录
        PayLog payLog = new PayLog();
        payLog.setTotalAmount(orderInfo.getIntergral() + "");
        payLog.setPayType(PayLog.PAY_TYPE_INTERGRAL);  // 积分支付
        payLog.setTradeNo(orderNo);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        payLog.setNotifyTime(simpleDateFormat.format(new Date()));
        payLogMapper.insert(payLog);
        // 2 远程调用积分服务进行支付
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setInfo(orderInfo.getProductName());
        operateIntergralVo.setUserId(orderInfo.getUserId());
        operateIntergralVo.setPk(orderNo);     // 业务主键(订单编号)
        operateIntergralVo.setValue(orderInfo.getIntergral());  // 消耗积分
        Result<String> result = intergralFeignApi.decrIntergral(operateIntergralVo);
        if (result == null || result.hasError()) {
            if ( result.getCode()==500602) {
                throw new BusinessException(SeckillCodeMsg.INTERGRAL_NOT_ENOUGH);
            } else {
                throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
            }
        }
        // 3 修改订单状态为支付的状态  积分支付
        int count = orderInfoMapper.changePayStatus(orderNo, OrderInfo.STATUS_ACCOUNT_PAID, OrderInfo.PAYTYPE_INTERGRAL);
        if (count==0) {
            throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
        }
    }

    @Override
    public void refundOnline(OrderInfo orderInfo) {
        // 4.1 插入流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setOutTradeNo(orderInfo.getOrderNo());              // 商品订单编号
        refundLog.setRefundAmount(orderInfo.getSeckillPrice() + "");  // 退款金额
        refundLog.setRefundTime(new Date());                          // 退款时间
        refundLog.setRefundType(OrderInfo.PAYTYPE_ONLINE);            // 退款类型  0-在线支付
        refundLog.setRefundReason("garbage 不要了");
        refundLogMapper.insert(refundLog);
        // 4.2 远程调用支付服务进行退款操作
        RefundVo refundVo = new RefundVo();
        refundVo.setOutTradeNo(orderInfo.getOrderNo());                // 交易订单号
        refundVo.setRefundAmount(orderInfo.getSeckillPrice() + "");    // 退款金额
        refundVo.setRefundReason("garbage 不要了");                     // 退款原因
        // result data:boolean 如果data 为true 表示退款成功 如果为false 表示退款失败
        Result<Boolean> result = alipayFeignApi.refundOnline(refundVo) ;
        if (result!=null && !result.hasError()) {
            if (!result.getData()) {
                throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
            }
        }
        // 4.3 修改订单状态为退款状态
        int count = orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
        }
        // 4.4 回补真实库存
        seckillProductMapper.incrStock(orderInfo.getSeckillId());
        // 4.5 回补预库存
        seckillProductService.syncRedisStockCount(orderInfo.getSeckillTime(),orderInfo.getSeckillId());
        // 4.6 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderInfo.getSeckillId());
    }

    @Override
    @GlobalTransactional
    public void refundIntergral(OrderInfo orderInfo) {
        //1 插入流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setOutTradeNo(orderInfo.getOrderNo());              // 商品订单编号
        refundLog.setRefundAmount(orderInfo.getSeckillPrice() + "");  // 退款金额
        refundLog.setRefundTime(new Date());                          // 退款时间
        refundLog.setRefundType(OrderInfo.PAYTYPE_INTERGRAL);            // 退款类型  1-积分支付
        refundLog.setRefundReason("garbage 不要了");
        // 2 远程调用支付服务进行退款操作
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setValue(orderInfo.getIntergral());                // 交易订单号
        operateIntergralVo.setPk(orderInfo.getOrderNo());    // 退款金额
        operateIntergralVo.setUserId(orderInfo.getUserId());                     // 退款原因
        operateIntergralVo.setInfo(orderInfo.getProductName());
        Result<String> result = intergralFeignApi.incrIntergral(operateIntergralVo) ;
        if (result==null && result.hasError()) {
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
        // 3 修改订单状态为退款状态
        int count = orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
        }
        //int i = 1 / 0;
        // 4 回补真实库存
        seckillProductMapper.incrStock(orderInfo.getSeckillId());
        // 5 回补预库存
        seckillProductService.syncRedisStockCount(orderInfo.getSeckillTime(),orderInfo.getSeckillId());
        // 6 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderInfo.getSeckillId());
    }
}
